<template>
  <div class="login-container">
    <!-- 顶部 -->
    <div class="absolute right-10 top-10 flex items-center gap20px">
      <el-switch v-model="isDark" inline-prompt :active-icon="Moon" :inactive-icon="Sunny" @change="toggleTheme" />
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <!-- 登录表单 -->
    <el-card class="!border-none !bg-transparent !rounded-4% w-100 <sm:w-85">
      <div class="text-center relative">
        <h2>{{ defaultSettings.title }}</h2>
      </div>

      <el-form ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <div class="flex-y-center w-full">
            <svg-icon icon-class="user" class="mx-2" />
            <el-input v-model="loginData.username" :placeholder="$t('form.1')" name="email" size="large"
              class="h-[48px]" />
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <div class="flex-y-center w-full">
            <svg-icon icon-class="lock" class="mx-2" />
            <el-input v-model="loginData.password" :placeholder="$t('form.2')" type="password" name="password"
              @keyup="checkCapslock" @keyup.enter="handleLogin" size="large" class="h-[48px] pr-2" show-password />
          </div>
        </el-form-item>
        <!-- 选择语言 -->
        <!-- <el-form-item prop="language">
          <div class="flex-y-center w-full">
            <svg-icon icon-class="captcha" class="mx-2" />
            <el-select v-model="loginData.language" size="large">
              <el-option v-for="item in langList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
        </el-form-item> -->
        <!-- 登录按钮 -->
        <el-button :loading="loading" type="primary" size="large" class="w-full" @click.prevent="handleLogin">
          {{$t("form.5") }}
        </el-button>
      </el-form>
    </el-card>
    <Validator ref="validatorRef" @subClick="verifyFn" />
  </div>
</template>

<script setup>
import { useSettingsStore, useUserStore } from "@/stores";
import router from "@/router";
import { defaultSettings, ThemeEnum } from "@/settings";
import AuthAPI from "@/api/auth";
const validatorRef = ref(null)
// Stores
const userStore = useUserStore();
const settingsStore = useSettingsStore();

// Internationalization
const { t } = useI18n();

// Reactive states
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const icpVisible = ref(true);
const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref(ElForm); // 登录表单ref
const { height } = useWindowSize();
const langList = [
  { label: "使用简体中文", value: "zh" },
  { label: "ใช้ภาษาไทย", value: "th" },
  { label: "Dùng tiếng Việt", value: "vn" },
  { label: "Use English", value: "en" },
];

const loginData = ref({
  username: "",
  password: "",
  remember: true,
  language: langList[0].value,
  // pa_google: "",
});
const loginRules = computed(() => {
  return {
    username: [{ required: true, trigger: "blur", message: t("hint.72"), },],
    password: [{ required: true, trigger: "blur", message: t("hint.5"), }]
  };
});
const route = useRoute();
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      userStore.login(loginData.value).then((s) => {
        if (s.two_factor) {

          validatorRef.value.showFn('verify')
        } else if (!s.enabled_two_factor_authentication) {
          validatorRef.value.showFn('bind')
        } else {
          loginOk()
        }
      }).finally(() => {
        loading.value = false;
      });
    }
  });
};
const verifyFn = ({ code, type }) => {
  console.log(code, type);
  if (type === 'verify') {
    AuthAPI.twoFactorChallenge({ code: code }).then(({ data }) => {
      userStore.setToken(`${data.token_type} ${data.token}`)
      validatorRef.value.hideFn()
      loginOk()
    }).catch(e => {
      validatorRef.value.hideFn(true)
    }).finally(() => { })
  } else {
    AuthAPI.verifyTwo({ code: code }).then(s => {
      userStore.setToken(`${data.token_type} ${data.token}`)
      validatorRef.value.hideFn()
      loginOk()
    }).catch(e => {
      validatorRef.value.hideFn(true)
    }).finally(() => {
    })
  }
}
const loginOk = () => {
  const query = route.query;
  const redirect = (query.redirect) ?? "/";
  const otherQueryParams = Object.keys(query).reduce(
    (acc, cur) => {
      if (cur !== "redirect") {
        acc[cur] = query[cur];
      }
      return acc;
    },
    {}
  )
  router.push({ path: redirect, query: otherQueryParams });
}

const bindGoogle = async () => {
  loading.value = true
  const codeData = await AuthAPI.twoQrCode()
  const keyData = await AuthAPI.twoKey()
  console.log(codeData, keyData);
  loading.value = false

  ElMessageBox.confirm(
    `<div class="text-end py-20px">
      <div class="flex pb-20px gap-5px">
        <span class="w-100px">${t('label.95')}：</span>
        ${codeData.data.svg}
      </div>
      <p class="flex gap-5px">
        <span class="w-100px">${t('label.96')}：</span>
        <span class="text-teal text-18px">${keyData.data.secret_key}</span> </p>
      </div>` ,
    {
      title: t("hint.99"),
      dangerouslyUseHTMLString: true,
      confirmButtonText: t("btn.12")
    }).then(s => {
      ElMessageBox.prompt(t("hint.100"), t("hint.1"), {
        inputPattern: /\S/,
        inputErrorMessage: t("hint.2"),
        confirmButtonText: t("btn.1"),
        cancelButtonText: t("btn.11"),
      }).then(({ value }) => {
        AuthAPI.verifyTwo({ code: value }).then(s => {
          loginOk()
        }).finally(() => { })
      }).catch(e => {
        bindGoogle()
      })
    }).catch(e => {
      // bindGoogle()
    })

}
/** 主题切换 */
const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

/** 根据屏幕宽度切换设备模式 */
watchEffect(() => {
  if (height.value < 600) {
    icpVisible.value = false;
  } else {
    icpVisible.value = true;
  }
});

/** 检查输入大小写 */
const checkCapslock = (event) => {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
};

onMounted(() => {
  // getCaptcha();
});

</script>

<style lang="scss" scoped>
html.dark .login-container {
  background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;
}

.login-container {
  overflow-y: auto;
  background: url("@/assets/images/login-bg.jpg") no-repeat center right;

  @apply wh-full flex-center;

  .login-form {
    padding: 30px 10px;
  }
}

.el-form-item {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

:deep(.el-select) {
  .el-select__wrapper {
    padding-left: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}
</style>